<template>
  <div>
    <Card>
      <Button style="margin: 10px 10px 10px 0;" type="primary" @click="add">添加</Button>
      <br>
      <template>
        <i-switch v-model="loading"/>
      </template>
      <tables ref="tables" editable searchable search-place="top"
              v-model="tableData" :columns="columns" :loading="loading"
              @on-delete="handleDelete"
              @on-filter-change="handleFilterChange"/>
      <div style="text-align: center; margin:16px 0">
        <!--.sync修饰符是一个语法糖，iView的Page组件内部是通过$emit('update:current')触发时间的-->
        <Page
          :total="total"
          :current.sync="current"
          :page-size="page_size"
          show-sizer
          @on-change="getData"
          @on-page-size-change="handleChangeSize"></Page>
      </div>
      <Button style="margin: 10px 0;" type="primary" @click="exportCsv">导出为Csv文件</Button>
      <Button style="margin: 10px 20px;" type="primary" @click="exportExcel">导出为Excel文件</Button>
      <Modal title="添加" v-draggable="options" v-model="modalVisible" @on-ok="submitOn('formData')">
        <template>
          <Form :model="formData" ref="formData" :rules="ruleValidate" :label-width="80">
            <FormItem label="任务名称" prop="jobName">
              <Input v-model="formData.jobName" placeholder="Enter something..."></Input>
            </FormItem>
            <FormItem label="执行时间" prop="cron">
              <Input v-model="formData.cron" placeholder="Enter something..."></Input>
            </FormItem>
            <FormItem label="任务类名" prop="clazzPath">
              <Input v-model="formData.clazzPath" placeholder="Enter something..."></Input>
            </FormItem>
            <!--<FormItem label="Select">-->
            <!--<Select v-model="formData.select">-->
            <!--<Option value="beijing">New York</Option>-->
            <!--<Option value="shanghai">London</Option>-->
            <!--<Option value="shenzhen">Sydney</Option>-->
            <!--</Select>-->
            <!--</FormItem>-->
            <FormItem label="Text">
              <Input v-model="formData.textarea" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                     placeholder="Enter something..."></Input>
            </FormItem>
          </Form>
        </template>
      </Modal>
    </Card>

  </div>
</template>

<script>
  import Tables from '_c/tables'
  import { getScheduleDataGrid, addScheduleTask } from '@/api/data'
  import axios from '@/libs/api.request'

  export default {
    name: 'schedule_page',
    components: {
      Tables,
      getScheduleDataGrid,
      addScheduleTask
    },
    data () {
      return {
        loading: false,
        total: 0,
        current: 1, // 请求第几页
        size: 10, // 一页请求多少条数据
        page_size: 10,
        winData: undefined,
        modalVisible: false,
        formData: {
          jobName: '',
          clazzPath: '',
          cron: ''
        },
        ruleValidate: {
          jobName: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
          clazzPath: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
          cron: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ]

        },
        filterType: undefined,
        options: {
          trigger: '.ivu-modal-body',
          body: '.ivu-modal',
          recover: true
        },
        columns: [
          { title: '', key: 'id', visible: false, type: 'index', width: 40 },
          {
            title: 'jobName',
            key: 'jobName',
            sortable: true,
            filters: [
              {
                label: 'Greater than 25',
                value: 1
              },
              {
                label: 'Less than 25',
                value: 2
              }
            ],
            filterMultiple: false,
            /* filterMethod (value, row) {
              if (value === 1) {
                return row.age > 25;
              } else if (value === 2) {
                return row.age < 25;
              }
            } */
            filterRemote (value, row) {
              localStorage.setItem('aa', value)
              this.$parent.$parent.filterType = value
            }

          },
          { title: 'cron', key: 'cron', editable: true },
          { title: 'clazzPath', key: 'clazzPath' },
          {
            /* options: ['delete'],
            button: [
              (h, params, vm) => {
                return h('Poptip', {
                  props: {
                    confirm: true,
                    title: '你确定要删除吗?'
                  },
                  on: {
                    'on-ok': () => {
                      vm.$emit('on-delete', params)
                      vm.$emit('input', params.tableData.filter((item, index) => index !== params.row.initRowIndex))
                    }
                  }
                }, [
                  h('Button', '自定义删除')
                ])
              }
            ] */
            title: 'Action',
            key: 'action',
            width: 200,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      axios.request({
                        url: 'job/startJob/' + params.row.id,
                        method: 'post'
                      }).then(res => {
                        this.getData()
                        this.$Message.success('Success!')
                      })
                    }
                  }
                }, '启动'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      axios.request({
                        url: 'job/pauseJob/' + params.row.id,
                        method: 'post'
                      }).then(res => {
                        this.getData()
                        this.$Message.success('Success!')
                      })
                    }
                  }
                }, '暂停'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.modalVisible = true
                      this.formData = params.row
                    }
                  }
                }, '更新'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      axios.request({
                        url: 'job/del/' + params.row.id,
                        method: 'post'
                      }).then(res => {
                        this.getData()
                        this.$Message.success('Success!')
                      })
                    }
                  }
                }, '删除')
              ])
            }

          }
        ],
        tableData: []
      }
    },
    methods: {
      handleDelete (params) {
        console.log(params)
      },
      exportCsv () {
        this.$refs.tables.exportCsv({
          filename: `table-${(new Date()).valueOf()}.csv`
        })
      },
      exportExcel () {
        axios.request({
          url: 'excel/exportExcel',
          //data: me.formData,
          method: 'post',
          responseType: 'blob'
        }).then((res) => {
          console.log(res)
          const link = document.createElement('a')
          let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob);
          let num = ''
          for(let i=0;i < 10;i++){
            num += Math.ceil(Math.random() * 10)
          }
          link.setAttribute('download', '用户_' + num + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }).catch(error => {
          this.$Notice.error({
            title: '错误',
            desc: '网络连接错误'
          })
          console.log(error)
        })

      },
      handleFilterChange () { // 触发filterRemote属性,对远程的数据进行过滤
        localStorage.getItem('aa')
        let me = this
        let pars = { 'task': localStorage.getItem('aa') }

        getScheduleDataGrid(pars).then(res => {
          me.tableData = []
        })
      },
      handleChangeSize (v) {
        this.page_size = v
        this.getData()
      },
      add () {
        this.modalVisible = true
      },
      submitOn (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$Message.success('Success!')
          } else {
            this.$Message.error('Fail!')
          }
        })
        let me = this
        // addScheduleTask(this.formData).then(function (response) {
        //   me.getData()
        //   me.formData = {}
        // })

        axios.request({
          url: 'job/addJob',
          data: me.formData,
          method: 'post'
        }).then(res => {
          me.getData()
          me.formData = {}
        })
      },
      getData () {
        this.loading = true
        let pars = { current: this.current, size: this.page_size }
        /* getScheduleDataGrid(pars).then(res => {
          this.tableData = res.data.result.content
          this.total = res.data.result.totalElements
          this.loading = false
        }) */

        axios.request({
          url: 'job/' + pars.current + '/' + pars.size,
          method: 'get'
        }).then(res => {
          this.tableData = res.data.result.content
          this.total = res.data.result.totalElements
          this.loading = false
        })
      }

    },
    mounted () {
     this.getData()
    }
  }
</script>

<style>
  .ivu-modal-wrap {
    top: 10%;
  }
</style>
